package cn.jtool.dig.common.netty.hander;

import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketBody;
import cn.jtool.dig.common.model.PacketHeader;
import cn.jtool.dig.common.netty.supports.ByteBuffer;
import cn.jtool.dig.common.netty.supports.Constants;
import cn.jtool.dig.common.netty.supports.Convert;
import cn.jtool.dig.common.netty.supports.PacketProcessing;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

@Slf4j
public class TunnelEncoder extends MessageToByteEncoder<Packet> {

    private final boolean debug;

    private final String name;

    public TunnelEncoder(String name, boolean debug) {
        this.debug = debug;
        this.name = name;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Packet packet, ByteBuf byteBuf) throws Exception {
        PacketHeader header = packet.getHeader();
        PacketBody body = packet.getBody();

        ByteBuffer buffer = new ByteBuffer();
        buffer.write(header.toBytes());
        if(Objects.nonNull(body)) {
            buffer.write(body.getBytes());
        }
        buffer.writeByte(PacketProcessing.checkPackage(buffer.readAll()));
        byte[] escape = PacketProcessing.escape(buffer.readAll(), Constants.AGENT_ESCAPE, Constants.AGENT_TO_ESCAPE);

        ByteBuffer finalBytes = new ByteBuffer();
        finalBytes.writeByte(0x5B);
        finalBytes.write(escape);
        finalBytes.writeByte(0x5D);
        byteBuf.writeBytes(finalBytes.readAll());

        if(this.debug){
            log.info("{} 发送数据 : {}", this.name, Convert.bytesToHexString(finalBytes.readAll()));
        }
    }
}
